<?php
require_once('./extends/model/WeiboModel.class.php');
/**                                          
 * 微博操作
 * @author M2
 * @version 1.0
 * create Date 2013-04-27
 */
class OperateModel extends WeiboModel{
   var $tableName = 'weibo';
   /**
    * 获取保存路径
    */
   function getSavePath(){
        $savePath = SITE_PATH.'/data/uploads/miniblog';
        if( !file_exists( $savePath ) ) mk_dir( $savePath  );
        return $savePath;
    }

	/**
	 * Topic搜索	
	 * @param string $map 条件
	 * @param string $order 排序
	 * @param int $uid 用户ID
	 * @param boolean $limit 分页
	 */
	function doSearchTopic($map,$order,$uid,$limit = true) {
		if (!is_string($map))
			return false;
		$map .= trim($map)?' AND isdel = 0':'isdel = 0';
    	$maskHotTopic = model('Data')->get('weibo:maskHotTopic');
		if( $maskHotTopic ){
			$arr_MaskHotTopic = explode('|', trim($maskHotTopic,'|'));
			foreach($arr_MaskHotTopic as $v){
				$map .= " AND content NOT LIKE '%#{$v}#%' ";
			}
		}
		if($limit){
		    $list = $this->field('weibo_id')->where($map)->order($order)->findPage(20);
		    $weibo_id_list = common('Array')->getSubByKey($list['data'],'weibo_id');
		    $list['data'] = $this->getWeiboDetail($weibo_id_list);
		}else{
		    $result = $this->field('weibo_id')->where($map)->order($order)->select();
		    $list['data'] = $this->getWeiboDetail($result);
		    if(empty($result)) return false;
		}
		//缓存被转发微博的详情, 作者信息, 被转发微博的作者信息
    	$ids = common('Array')->getSubByKeyArray($list['data'], 'weibo_id,transpond_id,uid');
    	$transpond_list = $this->getWeiboDetail($ids['transpond_id']);
    	// 本页的用户IDs = 作者IDs + 被转发微博的作者IDs
    	$ids['uid'] = array_merge($ids['uid'], common('Array')->getSubByKey($transpond_list, 'uid'));
    	model('User')->setUserObjectCache($ids['uid']);
		$weibo_ids = common('Array')->getSubByKey($list['data'], 'weibo_id');
		foreach($list['data'] as $key=>$value){
			$value['is_favorited'] = model('Favorite')->isFavorited($value['weibo_id'], $uid, $weibo_ids);
			$list['data'][$key] = $this->getOne($value['weibo_id'], $value);
		}
		return $list;
	}

	/**
	 * 获取未取出来的新微博条数
	 * @param int $uid 用户ID
	 * @param int $lastId 最后一条微博ID
	 * @param string $type 微博类型
	 * @param int $follow_gid 分组ID
	 */
	function countNew($uid,$lastId,$type=null,$follow_gid=null){
	    $lastId = intval($lastId);
	    if(empty($lastId)) return 0;
        return $this->__optToNew( $uid,$lastId,$type,$follow_gid );
	}

	/**
	 * 加载最新微博	
	 * @param int $uid 用户ID
	 * @param int $lastId 最后一条微博ID
	 * @param string $limit 是否分页
	 * @param string $type 微博类型
	 * @param int $follow_gid 分组ID
	 * @return array|int
	 */
	function loadNew($uid,$lastId,$limit,$type=null,$follow_gid=null){
	    return $this->__optToNew( $uid,$lastId,$type,$follow_gid,$limit);
	}
	
	function getNewWeibo($uid,$lastId,$follow_gid=null) {
		$map = "weibo_id > {$lastId} and isdel=0";
		if($uid > 0){
			$followCount = model('Follow')->getUserFollowCount($uid);
			if($followCount){
				if(!empty($follow_gid)){
					$fids = model('FollowGroup')->getUsersByGroup($uid,$follow_gid);
					$map.=' AND uid IN ('.implode(',',$fids).')';
				}else{
					$map.=" AND ( uid IN (SELECT fid FROM {$this->tablePrefix}weibo_follow WHERE uid=$uid AND type=0) OR uid={$uid} )";
				}
			}else{
				$map.=' AND uid = '.$uid;
			}
		}
		$list = $this->field('weibo_id')->where($map)->order('weibo_id DESC')->select();
		unset($map);
		//取出微博的实际数据
		$weibo_id_list = common('Array')->getSubByKey($list,'weibo_id');
		$data= $this->getWeiboDetail($weibo_id_list);
		$result = array();
		foreach( $data as $key=>$value){
			$result[] = $this->getOne($value['weibo_id'],$value);
		}
		$list['data'] = $result;
		return $list;
	}
	
	/**
	 * 加载最新微博
	 * @param int $uid 用户ID
	 * @param int $lastId 最后一条微博ID
	 * @param string $limit 是否分页
	 * @param string $type 微博类型
	 * @param int $follow_gid 分组ID
	 */
	private function __optToNew($uid,$lastId,$type='index',$follow_gid=null,$limit = 0,$since = false){
		if(!empty($type) && $type >0){
	        $type_str = " and type=".intval($type);
		}
		if($type==='original'){
			$type_str = " and transpond_id=0";
	    }
		if($since){
	        if($lastId >0){
	            $weiboId = "weibo_id<{$lastId} and";
	        }
	    }else{
	        if($lastId >0){
	            $weiboId = "weibo_id>{$lastId} and";
	        }
	    }
	    $map="{$weiboId} isdel=0 {$type_str}";
		if($uid>0){
			$followCount = model('Follow')->getUserFollowCount($uid);
			if($followCount){
				if(!empty($follow_gid)){
					$fids = model('FollowGroup')->getUsersByGroup($uid,$follow_gid);
					$map.=' AND uid IN ('.implode(',',$fids).')';
				}else{
					$map.=" AND ( uid IN (SELECT fid FROM {$this->tablePrefix}weibo_follow WHERE uid=$uid AND type=0) OR uid={$uid} )";
				}
			}else{//无关注时.数据为空.
				$map.=' AND uid = '.$uid;
			}
		}
	    if($limit){
	        $list = $this->field('weibo_id')->where($map)->order('weibo_id DESC')->limit($limit)->select();
			unset($map);
	        //取出微博的实际数据
	        $weibo_id_list = common('Array')->getSubByKey($list,'weibo_id');
	        $data= $this->getWeiboDetail($weibo_id_list);

	        $result = array();
	        foreach( $data as $key=>$value){
	            $result[] = $this->getOne($value['weibo_id'],$value);
	        }
	        $list['data'] = $result;
	    }else{
			$list = $this->where($map)->count();
	    }
	    return $list;
	}
	
	/**
	 * 设置用户积分
	 * @param int $uid 用户ID
	 * @param string $creditType 积分类型
	 */
	public function setUserCredit($uid,$creditType){
		$credit_Type = M('credit_type')->select();
		$creditValue = M('credit_setting')->where("name='".$creditType."'")->select();
		$creditUser = M('credit_user')->where("uid=".$uid)->select();
		$strSql="";
		$db_prefix  = C('DB_PREFIX');
		if(count($creditUser)>0){
			$strSql="UPDATE ".$db_prefix."credit_user SET ";
			$link="";
			foreach($credit_Type as $v){
				$strSql=$strSql.$link.$v['name']."=ifnull(".$v['name'].",0)+ifnull(".$creditValue[0][$v['name']].",0)" ;
				$link=",";
			}
			$strSql=$strSql." where uid=".$uid;
			$res=M('credit_user')->query($strSql);
		}else {
			$id = M('credit_user')->max('id');
			$value['id']=$id+1;
			$value["uid"] = $uid;
			foreach($credit_Type as $v){
				$value[$v['name']] = intval($creditValue[0][$v['name']]);
			}
			$res = M('credit_user')->data($value)->add();
		}
	}
}